export default class GameControler {
  size: string = '40vw'
  keySize: string = '14vw'
  backgroundImage: string = './assets/control-panel.png'
  keyImage: string = './assets/control-key.png'
  isDrag:boolean = false
  currentRadiuns:number = 0
  currentAngle:number = 0
  constructor(parent: HTMLElement) {
    let mainPanle = document.createElement('div')
    mainPanle.style.width = this.size
    mainPanle.style.height = this.size
    mainPanle.style.backgroundImage = `url(${this.backgroundImage})`
    mainPanle.style.backgroundSize = 'contain'
    mainPanle.style.position = 'fixed'
    mainPanle.style.bottom = '0'
    mainPanle.style.left = '0'
    parent.appendChild(mainPanle)

    let key = document.createElement('div')
    key.style.width = this.keySize
    key.style.height = this.keySize
    key.style.backgroundImage = `url(${this.keyImage})`
    key.style.backgroundSize = 'contain'
    key.style.position = 'absolute'
    key.style.bottom = this.relPos
    key.style.left = this.relPos
    mainPanle.appendChild(key)
    this.regEvent(mainPanle, key)

  }
  public get relPos(): string {
    return parseInt(this.size) / 2 - parseInt(this.keySize) / 2 + 'vw'
  }
  regEvent(panle: HTMLElement, key: HTMLElement) {
    let cx = panle.offsetLeft + panle.clientWidth / 2
    let cy = panle.offsetTop + panle.clientHeight / 2
    let max = panle.clientWidth / 2
    key.addEventListener('touchstart', e => {
      this.isDrag = true
    })
    panle.addEventListener('touchmove', e => {
      if (!this.isDrag) return
      let { pageX: x, pageY: y } = e.touches[0]
      let tx = x - cx,
        ty = y - cy
      let radius = (tx ** 2 + ty ** 2) ** 0.5
      if (radius <= max) {
        key.style.left = x - panle.offsetLeft - key.offsetWidth / 2 + 'px'
        key.style.top = y - panle.offsetTop - key.offsetHeight / 2 + 'px'
      } else {
        let ax = (max * tx) / radius
        let ay = (max * ty) / radius
        key.style.left = ax + max - key.offsetWidth / 2 + 'px'
        key.style.top = ay + max - key.offsetWidth / 2 + 'px  '
      }
      let radiuns = Math.atan2(ty, tx)
      let angle = (radiuns * 180 / Math.PI + 360) % 360
      this.currentRadiuns = radiuns
      this.currentAngle = angle
    })
    panle.addEventListener('touchend', e => {
      this.isDrag = false
      key.style.left = this.relPos
      key.style.top = this.relPos
    })
  }
}
